package cn.cnhis.online.customerView;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import cn.cnhis.online.BuildConfig;
import cn.cnhis.online.R;
import cn.cnhis.online.activity.main.view.MainActivity;
import cn.cnhis.online.base.ActivityStack;
import cn.cnhis.online.mymodule.BaseApplication;
import cn.cnhis.online.mymodule.Constants;
import cn.cnhis.online.mymodule.sp.MySpUtils;

public class NotificationHelper {

    private static final String CHANNEL_ID = "channel_id";   //通道渠道id
    public static final String CHANEL_NAME = "chanel_name"; //通道渠道名称
    private static NotificationManager notificationManager;
    private static NotificationHelper notificationHelper;

    public static NotificationHelper getInstance(Context context) {
        if (notificationHelper == null) {
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            return new NotificationHelper();
        }
        return notificationHelper;
    }

    @TargetApi(Build.VERSION_CODES.O)
    public void show(Context context, String message) {
        String title = null;
        String description = null;

        try {
            JSONObject jsonObject = new JSONObject(message);
            String userId = jsonObject.getString("to");
            String useInfo = MySpUtils.getUseInfo(context.getApplicationContext());
            if (BuildConfig.DEBUG) Log.d("NotificationHelper", "useInfo---->"+ useInfo);
            JSONObject userObj = new JSONObject(useInfo);
            JSONObject sysusers = userObj.getJSONObject("sysusers");
            if (BuildConfig.DEBUG) Log.d("NotificationHelper", "userObj:" + userObj);
            if (BuildConfig.DEBUG) Log.d("NotificationHelper", "sysusers:" + sysusers);

            if (useInfo != null) {
                String id = String.valueOf(sysusers.getLong("id"));
                if (!userId.equals(id)) {
                    return;
                } else {
                    String sysLoginSessionId = userObj.getString("sysLoginSessionId");
                    jsonObject.put("sysLoginSessionId", sysLoginSessionId);
                    message = jsonObject.toString();
                    if (BuildConfig.DEBUG) Log.d("NotificationHelper", "message--->" + message);
                }
            } else {
                return;
            }

            title = jsonObject.getString("title");
            description = jsonObject.getString("description");
            if (BuildConfig.DEBUG) Log.d("NotificationHelper", "title==" + title);
            if (BuildConfig.DEBUG) Log.d("NotificationHelper", "description==" + description);

            if (description != null) {
                if (description.length() > 30) {
                    description = description.substring(0, 30) + "...";
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        NotificationChannel channel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建 通知通道  channelid和channelname是必须的（自己命名就好）
            channel = new NotificationChannel(CHANNEL_ID, CHANEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);//是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN);//小红点颜色
            channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
        }
        Intent intent = null;
        PendingIntent pendingIntent = null;
        if (BuildConfig.DEBUG) Log.d("NotificationHelper", "message 112===>" + message);
//        if (BaseApplication.getINSTANCE() == null) {
//            if (BuildConfig.DEBUG) Log.d("NotificationHelper", "1111");
//            Context mContext = context.getApplicationContext();
//            intent = new Intent(Intent.ACTION_MAIN);
//            intent.putExtra(Constants.MESSAGE_KEY, message);
//            intent.addCategory(Intent.CATEGORY_LAUNCHER);
//            intent.setClass(context, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//            pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
//        } else {
        if (BuildConfig.DEBUG) Log.d("NotificationHelper", "222");
        intent = new Intent();
        intent.setAction(Constants.MESSAGE);
        intent.putExtra(Constants.MESSAGE_KEY, message);
//        Bundle bundle = new Bundle();
//        bundle.putString(message, Constants.MESSAGE_KEY);
//        intent.putExtra(Constants.MESSAGE_KEY, bundle);
        intent.setClass(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);
//        }
        Notification notification = null;

        //获取Notification实例   获取Notification实例有很多方法处理    在此我只展示通用的方法（虽然这种方式是属于api16以上，但是已经可以了，毕竟16以下的Android机很少了，如果非要全面兼容可以用）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //向上兼容 用Notification.Builder构造notification对象
            notification = new Notification.Builder(context, CHANNEL_ID)
                    .setContentTitle(title)
                    .setContentText(description)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_code_left)
                    .setColor(Color.parseColor("#FEDA26"))
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.lancher))
                    .setContentIntent(pendingIntent)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .build();

        } else {
            //向下兼容 用NotificationCompat.Builder构造notification对象
            notification = new NotificationCompat.Builder(context)
                    .setContentTitle(title)
                    .setContentText(description)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.lancher))
                    .setSmallIcon(R.drawable.ic_code_left)
                    .setColor(Color.parseColor("#FEDA26"))
                    .setContentIntent(pendingIntent)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .build();
        }

        //发送通知
        int notifiId = (int) System.currentTimeMillis();
        //创建一个通知管理器
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(notifiId, notification);

    }

    public NotificationManager getNotificationManager() {
        return notificationManager;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //8.0手机以上
            if (((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).getImportance() == NotificationManager.IMPORTANCE_NONE) {
                return false;
            }
        }

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;

        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }



}
